var $queryForm = $("#queryForm");
var $dataContainer = $("#dataContainer");
var $statisticsContainer = $("#statisticsContainer");
$('.js-date').datetimepicker({
    format: 'yyyy-mm-dd',
    autoclose: true,
    todayBtn: true,
    todayHighlight: true,
    startView: 2,
    minView: 2,
    language: 'zh-CN',
    maxDate: 0,
});

// 点击查询
$queryForm.delegate('.js-submit', 'click', function() {
    loadPage();
})

// 点击导出
$queryForm.delegate('.js-export', 'click', function() {
        var query = $queryForm.serialize();
        var url = './export?' + query;
        window.location.href = url;
    })
    // 加载数据
function loadPage(pageIndex) {
    if (pageIndex) {
        $('input[name=pageNo]', $queryForm).val(pageIndex);
    }
    $queryForm.ajaxSubmit(function(resp) {
        if (resp.code != 0) {
            doAlert(resp.message || '网络异常！');
            return false;
        }
        if (resp.data['totalElements'] == 0) {
            $dataContainer.hide().siblings('.js-no-result').show();
        } else {
            $dataContainer.show().siblings('.js-no-result').hide();
        }
        var totalPage = resp.data['totalPages'];
        if (totalPage < 2) {
            $("#pageContainer").hide();
        } else {
            $("#pageContainer").show().createPage({
                pageCount: totalPage,
                totalCount: resp.data['totalElements'],
                current: pageIndex,
                backFn: loadPage
            });
        }
        $('.js-total', $statisticsContainer).text(resp.data['totalElements']);
        buildDataHtml(resp.data.content);
    })
}

// 显示数据
function buildDataHtml(itemList) {
    $dataContainer.empty();
    itemList.forEach(function(item) {
        var html = '<tr data-id="' + item.id + '">' +
            '<td>' + (item.name) + '</td>' +
            '<td>' + (item.mobile || '') + '</td>' +
            '<td>' + (item.email || '') + '</td>' +
            '<td>' + (item.nationality || '') + '</td>' +
            '<td>' + (item.countryAreaCode || '') + '</td>' +
            '<td>' + (item.workplace || '') + '</td>' +
            '<td>' + (item.createTime.substr(0, 16)) + '</td>' +
            '<td><a target="_blank" href="./detail?id=' + item.id + '">详情</a></td>' +
            '</tr>'
        $dataContainer.append(html);
    })
    showBtns();
}

$(document).ready(function() {
    loadPage(1)
});